<template>
  <div class="shop-cart-container" :style="{ backgroundColor: shopCartAllGoods.length === 0 ? '#fff' : '#f1f1f1' }">
    <div class="header">
      <van-nav-bar title="购物车" left-text="返回" :right-text="text" @click-right="onClickRight" left-arrow @click-left="$router.back()" />
    </div>
    <div class="empty" v-if="shopCartAllGoods.length === 0">
      <van-empty description="购物车空空如也！" :image="require('@/assets/cart_empty.jpg')" />
    </div>

    <!-- 购物袋中商品列表 -->
    <ul class="goods-list" v-else>
      <li class="goods-item" v-for="item in shopCartAllGoods" :key="item.cartId">
        <div class="check-box">
          <van-checkbox v-model="item.check" />
        </div>
        <div class="goods-content" @click="$router.push('/goods/detail/' + item.id)">
          <div class="goods-img">
            <van-image lazy-load :src="'http://www.dsl2023hcy.love:3004' + item.goods_img"></van-image>
          </div>
          <div class="goods-desc">
            <div class="goods-title">{{ item.goods_name }}</div>
            <div class="price-count">
              <div class="price">
                <span>￥</span>
                <span class="number">{{ dealPrice(item.goods_price)[0] }}</span>
                <span>.{{ dealPrice(item.goods_price)[1] }}</span>
              </div>
              <div class="count">
                <van-stepper :max="item.goods_stock" v-model="item.count" button-size="22" disable-input @minus="updateCount(item, 1)" @plus="updateCount(item, 0)" />
              </div>
            </div>
          </div>
        </div>
      </li>
    </ul>

    <!-- 选择地址 -->
    <van-popup v-model="show" position="bottom" round closeable z->
      <SelectAddress
        @setChosenAddressId="
          (val) => {
            chosenAddressId = val
          }
        "
        @editUserInfo="setUserNamePhone"
      ></SelectAddress>
    </van-popup>

    <!-- 提交订单 -->
    <div class="submit-bar" v-if="shopCartAllGoods.length > 0">
      <van-submit-bar button-text="删除" @submit="onSubmit" v-if="rightText === '退出管理'">
        <van-checkbox v-model="allChecked">全选</van-checkbox>
      </van-submit-bar>
      <van-submit-bar v-else :price="totalPrice" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="allChecked">全选</van-checkbox>
      </van-submit-bar>
    </div>
  </div>
</template>

<script>
import axios from '@/utils/request/request'
import SelectAddress from '@/components/user/order/SelectAddress.vue'
import { Notify } from 'vant'
export default {
  name: 'shopCart',
  data() {
    return {
      shopCartAllGoods: [],
      isEdit: false,
      text: '',
      showDelSelect: false,
      clickFlag: true,
      chosenAddressId: '',
      show: false
    }
  },
  components: { SelectAddress },
  computed: {
    // 动态更新选中商品总价格
    totalPrice() {
      let price = this.shopCartAllGoods
        .filter((item) => item.check)
        .reduce((total, item) => {
          total += parseFloat(item.goods_price) * item.count
          return total
        }, 0)
      return price * 100
    },
    // 全选按钮选中状态
    allChecked: {
      get() {
        let check = true
        this.shopCartAllGoods.some((item) => {
          if (!item.check) {
            return (check = false)
          }
        })
        return check
      },
      set(check) {
        this.shopCartAllGoods.forEach((item) => (item.check = check))
      }
    },
    rightText: {
      get() {
        if (this.isEdit && this.shopCartAllGoods.length > 0) {
          return (this.text = '退出管理')
        } else if (!this.isEdit && this.shopCartAllGoods.length > 0) {
          return (this.text = '管理')
        } else {
          return ''
        }
      },
      set(val) {
        if (this.isEdit && this.shopCartAllGoods.length > 0) {
          this.text = val
        } else if (!this.isEdit && this.shopCartAllGoods.length > 0) {
          this.text = val
        } else {
          this.text = val
        }
      }
    }
  },
  methods: {
    async setUserNamePhone() {
      this.show = false
      let ids = ''
      const goods_ids = []
      this.shopCartAllGoods
        .filter((item) => item.check)
        .forEach((item) => {
          ids += item.cartId + ','
          goods_ids.push({ id: item.id, count: item.count })
        })
      const params = {
        ids: ids.slice(0, -1),
        goods_ids: JSON.stringify(goods_ids),
        address_id: this.chosenAddressId
      }
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      // 发起请求提交订单
      try {
        const data = await axios.post('/user/cart/add/order', params)
        if (data.code === 0) {
          // 订单提交成功
          Notify({
            type: 'success',
            message: data.msg,
            duration: 500,
            onClose: () => {
              this.$router.push('/order/payment/' + data.data.orderId)
            }
          })
        } else if (data.code === 403 || data.msg === '身份认证错误') {
          // 登录过期
          localStorage.removeItem('user_token')
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 500,
            onClose: () => {
              localStorage.removeItem('user_token')
              this.$router.push('/login')
            }
          })
        } else {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 500
          })
        }
      } catch {
        Notify({
          type: 'danger',
          message: '订单提交失败!',
          duration: 100
        })
      } finally {
        this.$toast.clear()
      }
    },
    // 处理价格
    dealPrice(price) {
      const priceArr = price.toFixed(2).split('.')
      return priceArr
    },
    onClickRight() {
      if (this.isEdit && this.shopCartAllGoods.length > 0) {
        this.isEdit = false
        this.rightText = '退出管理'
      } else if (!this.isEdit && this.shopCartAllGoods.length > 0) {
        this.isEdit = true
        this.rightText = '管理'
      } else {
        this.isEdit = false
        this.rightText = ''
      }
    },
    // 获取购物车所有数据
    async getShopCartAllGoods() {
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      try {
        const data = await axios.get('/user/all/cart/goods')

        if (data.code === 0) {
          // 获取数据成功，对数据进行处理
          this.shopCartAllGoods = data.data.map((item) => {
            return {
              cartId: item.id,
              check: false,
              article_no: item.goods_data.article_no,
              bus_id: item.goods_data.bus_id,
              goods_img: item.goods_data.goods_img,
              goods_name: item.goods_data.goods_name,
              goods_price: item.goods_data.goods_price,
              goods_stock: item.goods_data.goods_stock,
              id: item.goods_data.id,
              specs: item.goods_data.specs,
              count: item.count
            }
          })
          if (this.shopCartAllGoods.length === 0) {
            this.rightText = ''
          }
        } else if (data.msg === '身份认证错误' || data.code === 403) {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000,
            onClose: () => {
              localStorage.removeItem('user_token')
              this.$router.push('/login')
            }
          })
        }
      } catch (err) {
        Notify({
          type: 'danger',
          message: '获取购物车数据失败!'
        })
      } finally {
        this.$toast.clear()
      }
    },
    // 提交订单onSubmit或删除购物车信息
    async onSubmit() {
      let ids = ''
      this.shopCartAllGoods.forEach((item) => {
        if (item.check) {
          ids += item.cartId + ','
        }
      })
      if (ids === '') return Notify({ type: 'danger', message: '至少选择一件商品！', duration: 500 })
      ids = ids.slice(0, -1)
      // 根据不同的场景完成不同的功能
      if (this.rightText === '退出管理') {
        // 删除购物车内容
        this.$toast.loading({
          message: '加载中...',
          duration: 0
        })
        try {
          const data = await axios.post('/user/del/cart/goods', {
            ids
          })

          if (data.code === 0) {
            // 删除成功
            this.getShopCartAllGoods()
          } else if (data.msg === '身份认证错误' || data.code === 403) {
            Notify({
              type: 'danger',
              message: data.msg,
              duration: 1000,
              onClose: () => {
                localStorage.removeItem('user_token')
                this.$router.push('/login')
              }
            })
          } else {
            Notify({
              type: 'danger',
              message: data.msg
            })
          }
        } catch (err) {
          Notify({
            type: 'danger',
            message: '删除失败!'
          })
        } finally {
          this.$toast.clear()
        }
      } else {
        // 提交订单
        this.show = true
      }
    },
    // 修改购物车商品数量
    async updateCount(goods, option) {
      event.stopPropagation() // 阻止冒泡
      if (goods.const < 1) return Notify({ type: 'danger', message: '数量至少1件噢！', duration: 500 })
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      let count = 0
      if (option === 1) {
        // 减少数据
        count = goods.count - 1
      } else {
        // 增加数据
        count = goods.count + 1
      }
      try {
        const data = await axios.post('/user/edit/cart/goods/count', {
          count,
          id: goods.cartId,
          goods_id: goods.id
        })

        if (data.code === 0) {
          // 修改数量成功
        } else {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 500
          })
          if (option === 1) {
            // 增加数据
            goods.count++
          } else {
            // 减少数据
            goods.count--
          }
        }
      } catch {
        if (option === 1) {
          // 增加数据
          goods.count++
        } else {
          // 减少数据
          goods.count--
        }
        Notify({ type: 'danger', message: '更改失败！' })
      } finally {
        this.$toast.clear()
      }
    }
  },
  created() {
    this.getShopCartAllGoods()
  }
}
</script>

<style lang="less" scoped>
.shop-cart-container {
  min-height: 100vh;
  padding-top: 46px;

  .empty {
    padding: 30px 0;
  }
  .icon.van-icon {
    font-size: 160px;
    color: #ccc;
  }
  .header {
    z-index: 1;
    position: fixed;
    top: 0;
    left: 0;
    height: 50px;
    width: 100%;
  }
  ::v-deep .van-empty {
    padding-top: 80px;
  }
  ::v-deep .van-nav-bar .van-icon {
    color: #323232;
  }
  ::v-deep .van-nav-bar__left .van-nav-bar__text {
    color: #323232;
  }
  ::v-deep .van-nav-bar__text {
    color: #ee0a24;
  }

  .goods-list {
    padding: 0 5px 100px;
    margin-top: 5px;

    .goods-item {
      padding: 10px 5px;
      background-color: #fff;
      border-radius: 10px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .check-box {
        flex-shrink: 0;
        padding: 0 5px;
      }

      .goods-content {
        flex: 1;
        flex-shrink: 0;
        display: flex;
        align-items: center;

        .goods-img {
          flex: 1;
          flex-shrink: 0;
        }

        .goods-desc {
          flex: 3;
          padding-left: 10px;
          flex-shrink: 0;

          .goods-title {
            width: 100%;
            font-size: 14px;
            font-weight: 700;
            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-line-clamp: 2; /*显示为两行，在第二行中显示为.......*/
            display: -webkit-box;
            -webkit-box-orient: vertical;
          }
          .price-count {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 10px;

            .price {
              font-size: 12px;

              span {
                color: #ee0a24;
                font-weight: 700;
              }

              .number {
                font-size: 20px;
              }
            }
          }
        }
      }
    }
  }

  .van-submit-bar {
    bottom: 46px;
    display: flex;
    width: 100%;

    .van-submit-bar__bar {
      width: 100%;
      align-items: center;
      justify-content: space-between;
    }
    .van-submit-bar__price--integer {
      font-weight: 600;
    }
  }
  ::v-deep .van-checkbox__icon--checked .van-icon {
    background-color: #ee0a24;
    border-color: #ee0a24;
  }
}
</style>
